import { defineStore } from "pinia";
import { ref, computed } from 'vue';

export const useCartStore = defineStore('cart', () => {
    // 1. state
    const cartList = ref([]);

    // 2. action
    const addCart = (good) => {
        const el = cartList.value.find((item) => item.skuId === good.skuId);
        console.log('el', el);
        if (el) {
            el.count += good.count;
        } else {
            cartList.value.push(good);
        }

    };


    const delCart = (skuId) => {
        const index = cartList.value.findIndex((item) => item.skuId === skuId);
        cartList.value.splice(index, 1);
    }

    const singleChange = (skuId) => {
        const item = cartList.value.find((item) => skuId === item.skuId);
        item.selected = !item.selected;
    }


    const allChecked = (selected) => {
        cartList.value.forEach((item) => item.selected = selected);
    }


    // 3. 计算属性
    const num = computed(() =>
        cartList.value.reduce((current, item) =>
            current + item.count
            , 0)
    );
    const totalPrice = computed(() => cartList.value.reduce((a, c) =>
        a + c.price * c.count
        , 0));
    const selectedCount = computed(() => cartList.value.filter((item) => item.selected).reduce((a, c) => a + c.count, 0));
    const selectedPrice = computed(() => cartList.value.filter((item) => item.selected).reduce((a, c) => a + c.price * c.count, 0));

    const isAll = computed(() => cartList.value.every(item => item.selected))
    return {
        cartList,
        num,
        totalPrice,
        isAll,
        selectedCount,
        selectedPrice,
        addCart,
        delCart,
        singleChange,
        allChecked
    }
}, {
    persist: true
})
